package org.jeecg.modules.online.cgform.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.online.cgform.common.CommonEntity;
import org.jeecg.modules.online.cgform.entity.OnlCgformButton;
import org.jeecg.modules.online.cgform.entity.OnlCgformEnhanceJs;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.model.HrefSlots;
import org.jeecg.modules.online.cgform.model.OnlColumn;
import org.jeecg.modules.online.cgform.model.OnlineConfigModel;
import org.jeecg.modules.online.cgform.model.OnlForeignKey;
import org.jeecg.modules.online.cgform.model.ScopedSlots;
import org.jeecg.modules.online.cgform.model.FieldModel;
import org.jeecg.modules.online.cgform.service.IOnlCgformFieldService;
import org.jeecg.modules.online.cgform.service.IOnlCgformHeadService;
import org.jeecg.modules.online.cgform.service.IOnlineService;
import org.jeecg.modules.online.cgform.util.EnhanceJsUtil;
import org.jeecg.modules.online.cgform.util.FieldSlotType;
import org.jeecg.modules.online.cgform.util.SqlSymbolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("onlineService")
public class OnlineServiceImpl implements IOnlineService {
    @Autowired
    private IOnlCgformFieldService onlCgformFieldService;
    @Autowired
    private IOnlCgformHeadService onlCgformHeadService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    public OnlineConfigModel queryOnlineConfig(OnlCgformHead head) {
        String id = head.getId();
        List<OnlCgformField> onlCgformFields = this.getFields(id);
        List<String> hideColumns = this.onlCgformFieldService.selectOnlineHideColumns(head.getTableName());
        List<OnlColumn> columns = new ArrayList<>();
        Map<String,List<DictModel>> dictOptions = new HashMap<>();
        List<HrefSlots> fieldHrefSlots = new ArrayList<>();
        List<OnlForeignKey> foreignKeys = new ArrayList<>();
        List<String> var9 = new ArrayList<>();
        Iterator<OnlCgformField> iterator = onlCgformFields.iterator();

        String mainField;
        while(iterator.hasNext()) {
            OnlCgformField onlCgformField = iterator.next();
            String dbFieldName = onlCgformField.getDbFieldName();
            String mainTable = onlCgformField.getMainTable();
            mainField = onlCgformField.getMainField();
            if (oConvertUtils.isNotEmpty(mainField) && oConvertUtils.isNotEmpty(mainTable)) {
                OnlForeignKey onlForeignKey = new OnlForeignKey(dbFieldName, mainField);
                foreignKeys.add(onlForeignKey);
            }

            if (1 == onlCgformField.getIsShowList() && !"id".equals(dbFieldName) && !hideColumns.contains(dbFieldName) && !var9.contains(dbFieldName)) {
                OnlColumn onlColumn = new OnlColumn(onlCgformField.getDbFieldTxt(), dbFieldName, onlCgformField.getFieldLength());
                String dictField = onlCgformField.getDictField();
                String fieldShowType = onlCgformField.getFieldShowType();
                if (oConvertUtils.isNotEmpty(dictField) && !FieldSlotType.POPUP.equals(fieldShowType)) {
                	List<DictModel> dicts = new ArrayList<>();
                    if (oConvertUtils.isNotEmpty(onlCgformField.getDictTable())) {
                    	dicts = this.sysBaseAPI.queryTableDictItemsByCode(onlCgformField.getDictTable(), onlCgformField.getDictText(), dictField);
                    } else if (oConvertUtils.isNotEmpty(onlCgformField.getDictField())) {
                    	dicts = this.sysBaseAPI.queryDictItemsByCode(dictField);
                    }

                    dictOptions.put(dbFieldName, dicts);
                    onlColumn.setCustomRender(dbFieldName);
                }

                List<DictModel> sysDictOption;
                if (FieldSlotType.SWITCH.equals(fieldShowType)) {
                	sysDictOption = SqlSymbolUtil.getYNDict(onlCgformField);
                    dictOptions.put(dbFieldName, sysDictOption);
                    onlColumn.setCustomRender(dbFieldName);
                }

                List<DictModel> tableDictOption;
                String dictTable;
                if (FieldSlotType.LINK_DOWN.equals(fieldShowType)) {
                	dictTable = onlCgformField.getDictTable();
                    CommonEntity commonEntity = (CommonEntity)JSONObject.parseObject(dictTable, CommonEntity.class);
                    tableDictOption = this.sysBaseAPI.queryTableDictItemsByCode(commonEntity.getTable(), commonEntity.getTxt(), commonEntity.getKey());
                    dictOptions.put(dbFieldName, tableDictOption);
                    onlColumn.setCustomRender(dbFieldName);
                    columns.add(onlColumn);
                    String linkField = commonEntity.getLinkField();
                    this.a(onlCgformFields, var9, columns, dbFieldName, linkField);
                }

                if (FieldSlotType.SEL_TREE.equals(fieldShowType)) {
                    String[] dictText = onlCgformField.getDictText().split(",");
                    List<DictModel> tableDictItems = this.sysBaseAPI.queryTableDictItemsByCode(onlCgformField.getDictTable(), dictText[2], dictText[0]);
                    dictOptions.put(dbFieldName, tableDictItems);
                    onlColumn.setCustomRender(dbFieldName);
                }

                if (FieldSlotType.CAT_TREE.equals(fieldShowType)) {
                	dictTable = onlCgformField.getDictText();
                    if (oConvertUtils.isEmpty(dictTable)) {
                        String filterSql = SqlSymbolUtil.getFilterSql(onlCgformField.getDictField());
                        tableDictOption = this.sysBaseAPI.queryFilterTableDictInfo("SYS_CATEGORY", "NAME", "ID", filterSql);
                        dictOptions.put(dbFieldName, tableDictOption);
                        onlColumn.setCustomRender(dbFieldName);
                    } else {
                        onlColumn.setCustomRender("_replace_text_" + dictTable);
                    }
                }

                if (FieldSlotType.SEL_DEPART.equals(fieldShowType)) {
                	sysDictOption = this.sysBaseAPI.queryAllDepartBackDictModel();
                    dictOptions.put(dbFieldName, sysDictOption);
                    onlColumn.setCustomRender(dbFieldName);
                }

                if (FieldSlotType.SEL_USER.equals(fieldShowType)) {
                	sysDictOption = this.sysBaseAPI.queryTableDictItemsByCode("SYS_USER", "REALNAME", "USERNAME");
                    dictOptions.put(dbFieldName, sysDictOption);
                    onlColumn.setCustomRender(dbFieldName);
                }

                if (fieldShowType.indexOf(FieldSlotType.FILE) >= 0) {
                    onlColumn.setScopedSlots(new ScopedSlots("fileSlot"));
                } else if (fieldShowType.indexOf(FieldSlotType.IMAGE) >= 0) {
                    onlColumn.setScopedSlots(new ScopedSlots("imgSlot"));
                } else if (fieldShowType.indexOf(FieldSlotType.EDITOR) >= 0) {
                    onlColumn.setScopedSlots(new ScopedSlots("htmlSlot"));
                } else if (fieldShowType.equals(FieldSlotType.DATE)) {
                    onlColumn.setScopedSlots(new ScopedSlots("dateSlot"));
                } else if (fieldShowType.equals(FieldSlotType.PCA)) {
                    onlColumn.setScopedSlots(new ScopedSlots("pcaSlot"));
                } else if(fieldShowType.equals(FieldSlotType.MONTH)){
                	onlColumn.setScopedSlots(new ScopedSlots("monthSlot"));
                } else {
                    onlColumn.setScopedSlots(new ScopedSlots("formatSlot"));
                }

                String jsEnhance = onlCgformField.getJsEnhance();
                if (!org.springframework.util.StringUtils.isEmpty(jsEnhance)) {
                    onlColumn.setJsEnhance(onlCgformField.getJsEnhance());
                }

                if (StringUtils.isNotBlank(onlCgformField.getFieldHref())) {
                	dictTable = "fieldHref_" + dbFieldName;
                    onlColumn.setHrefSlotName(dictTable);
                    fieldHrefSlots.add(new HrefSlots(dictTable, onlCgformField.getFieldHref()));
                }

                if ("1".equals(onlCgformField.getSortFlag())) {
                    onlColumn.setSorter(true);
                }

                if (!FieldSlotType.LINK_DOWN.equals(fieldShowType)) {
                	columns.add(onlColumn);
                }
            }
        }

        OnlineConfigModel onlineConfigModel = new OnlineConfigModel();
        onlineConfigModel.setCode(id);
        onlineConfigModel.setTableType(head.getTableType());
        onlineConfigModel.setFormTemplate(head.getFormTemplate());
        onlineConfigModel.setDescription(head.getTableTxt());
        onlineConfigModel.setCurrentTableName(head.getTableName());
        onlineConfigModel.setPaginationFlag(head.getIsPage());
        onlineConfigModel.setCheckboxFlag(head.getIsCheckbox());
        onlineConfigModel.setScrollFlag(head.getScroll());
        onlineConfigModel.setColumns(columns);
        onlineConfigModel.setDictOptions(dictOptions);
        onlineConfigModel.setFieldHrefSlots(fieldHrefSlots);
        onlineConfigModel.setForeignKeys(foreignKeys);
        onlineConfigModel.setHideColumns(hideColumns);
        List<OnlCgformButton> buttonList = this.onlCgformHeadService.queryButtonList(id, true);
        List<OnlCgformButton> showButtonList = new ArrayList<>();
        Iterator<OnlCgformButton> var25 = buttonList.iterator();

        while(var25.hasNext()) {
            OnlCgformButton var27 = var25.next();
            if (!hideColumns.contains(var27.getButtonCode())) {
            	showButtonList.add(var27);
            }
        }

        onlineConfigModel.setCgButtonList(showButtonList);
        OnlCgformEnhanceJs enhanceJs = this.onlCgformHeadService.queryEnhanceJs(id, "list");
        if (enhanceJs != null && oConvertUtils.isNotEmpty(enhanceJs.getCgJs())) {
        	mainField = EnhanceJsUtil.getJsFunction(enhanceJs.getCgJs(), buttonList);
        	onlineConfigModel.setEnhanceJs(mainField);
        }

        if ("Y".equals(head.getIsTree())) {
        	onlineConfigModel.setPidField(head.getTreeParentIdField());
        	onlineConfigModel.setHasChildrenField(head.getTreeIdField());
        	onlineConfigModel.setTextField(head.getTreeFieldname());
        }

        return onlineConfigModel;
    }

    private void a(List<OnlCgformField> onlCgformFields, List<String> var2, List<OnlColumn> onlColumns, String render, String linkFields) {
        if (oConvertUtils.isNotEmpty(linkFields)) {
            String[] linkFieldArr = linkFields.split(",");
            //String[] var7 = var6;

            for(int i = 0; i < linkFieldArr.length; ++i) {
                String linkField = linkFieldArr[i];
                Iterator<OnlCgformField> iterator = onlCgformFields.iterator();

                while(iterator.hasNext()) {
                    OnlCgformField onlCgformField = iterator.next();
                    String dbFieldName = onlCgformField.getDbFieldName();
                    if (1 == onlCgformField.getIsShowList() && linkField.equals(dbFieldName)) {
                        var2.add(linkField);
                        OnlColumn onlColumn = new OnlColumn(onlCgformField.getDbFieldTxt(), dbFieldName, onlCgformField.getFieldLength());
                        onlColumn.setCustomRender(render);
                        onlColumns.add(onlColumn);
                        break;
                    }
                }
            }
        }

    }

    public JSONObject queryOnlineFormObj(OnlCgformHead head, OnlCgformEnhanceJs onlCgformEnhanceJs) {
        JSONObject result = new JSONObject();
        String headId = head.getId();
        List<OnlCgformField> fields = this.onlCgformFieldService.queryAvailableFields(head.getId(), head.getTableName(), (String)null, false);
        List<String> disabledFields = this.onlCgformFieldService.queryDisabledFields(head.getTableName());
        EnhanceJsUtil.a(onlCgformEnhanceJs, head.getTableName(), fields);
        FieldModel fieldModel = null;
        if ("Y".equals(head.getIsTree())) {
        	fieldModel = new FieldModel();
        	fieldModel.setCodeField("id");
        	fieldModel.setFieldName(head.getTreeParentIdField());
        	fieldModel.setPidField(head.getTreeParentIdField());
        	fieldModel.setPidValue("0");
        	fieldModel.setHsaChildField(head.getTreeIdField());
        	fieldModel.setTableName(SqlSymbolUtil.getSubstring(head.getTableName()));
        	fieldModel.setTextField(head.getTreeFieldname());
        }

        JSONObject filedJson = SqlSymbolUtil.getFiledJson(fields, disabledFields, fieldModel);
        filedJson.put("table", head.getTableName());
        result.put("schema", filedJson);
        result.put("head", head);
        List<OnlCgformButton> buttons = this.onlCgformHeadService.queryButtonList(headId, false);
        if (buttons != null && buttons.size() > 0) {
        	result.put("cgButtonList", buttons);
        }

        if (onlCgformEnhanceJs != null && oConvertUtils.isNotEmpty(onlCgformEnhanceJs.getCgJs())) {
            String cgJs = EnhanceJsUtil.getCgJs(onlCgformEnhanceJs.getCgJs(), buttons);
            onlCgformEnhanceJs.setCgJs(cgJs);
            result.put("enhanceJs", EnhanceJsUtil.getCgJs(onlCgformEnhanceJs.getCgJs()));
        }

        return result;
    }

    public JSONObject queryOnlineFormObj(OnlCgformHead head) {
        OnlCgformEnhanceJs var2 = this.onlCgformHeadService.queryEnhanceJs(head.getId(), "form");
        return this.queryOnlineFormObj(head, var2);
    }

    private List<OnlCgformField> getFields(String cgformHeadId) {
        LambdaQueryWrapper<OnlCgformField> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OnlCgformField::getCgformHeadId, cgformHeadId);
        lambdaQueryWrapper.orderByAsc(OnlCgformField::getOrderNum);
        return this.onlCgformFieldService.list(lambdaQueryWrapper);
    }
}
